package com.wrt.produce.controller;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wrt.produce.source.DynamicDataSource;
import com.wrt.produce.util.DataBaseNameUtil;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;

/**
 * 首页接口
 * 
 * @author 文瑞涛
 * @date 2021年7月14日 下午2:58:53
 */
@RestController
@Log4j2
public class IndexController {

    @Autowired
    private DynamicDataSource dataSource;

    /**
     * 当前连接的数据库名称
     * 
     * @param request http请求
     * @return 数据库名称
     */
    @GetMapping("/currentDB")
    public ResponseEntity<String> currentDB(HttpServletRequest request) {
        DataSource tempDataSource;
        try {
            tempDataSource = dataSource.getDataSource(request.getSession().getId());
            if (tempDataSource == null) {
                tempDataSource = dataSource.getDataSource();
            }
        } catch (Exception e) {
            log.warn("获取数据源失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("内部服务器错误");
        }

        try (Connection connection = tempDataSource.getConnection()) {
            String dbUrl = connection.getMetaData().getURL();
            String dbName = DataBaseNameUtil.getDataBaseNameByUrl(dbUrl);
            return ResponseEntity.ok(dbName);
        } catch (SQLException e) {
            log.error("数据库连接错误", e);
            return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("服务不可用");
        }
    }
}